// pages/medication/medication.js
Page({
  data: {
    medicationName: '降压药',
    status: 'taken',
    notesValue: '',
    showConfirmDialog: false
  },

  onLoad() {
    // 获取设置的药品名称
    const settings = wx.getStorageSync('settings') || {};
    if (settings.medicationName) {
      this.setData({
        medicationName: settings.medicationName
      });
    }
  },

  radioChange(e) {
    this.setData({
      status: e.detail.value
    });
  },

  inputNotes(e) {
    this.setData({
      notesValue: e.detail.value
    });
  },

  submitRecord() {
    this.setData({
      showConfirmDialog: true
    });
  },

  confirmSubmit() {
    // 创建记录对象
    const record = {
      id: Date.now().toString(),
      medicationName: this.data.medicationName,
      status: this.data.status,
      notes: this.data.notesValue || '',
      recordTime: this.formatDateTime(new Date()),
      scheduledTime: this.getScheduledTime()
    };

    // 获取现有记录
    let medicationRecords = wx.getStorageSync('medicationRecords') || [];

    // 添加新记录到数组开头
    medicationRecords.unshift(record);

    // 保存到本地存储
    wx.setStorageSync('medicationRecords', medicationRecords);

    // 显示成功提示
    wx.showToast({
      title: '记录保存成功',
      icon: 'success',
      duration: 1500,
      success: () => {
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          });
        }, 1500);
      }
    });

    this.setData({
      showConfirmDialog: false
    });
  },

  cancelSubmit() {
    this.setData({
      showConfirmDialog: false
    });
  },

  formatDateTime(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');

    return `${year}-${month}-${day} ${hour}:${minute}`;
  },

  getScheduledTime() {
    const settings = wx.getStorageSync('settings') || {};
    const today = new Date().toISOString().split('T')[0];
    return settings.reminderTime ? `${today} ${settings.reminderTime}` : this.formatDateTime(new Date());
  },

  navigateBack() {
    wx.navigateBack({
      delta: 1
    });
  }
})